// 游戏渲染器
export class GameRenderer {
    constructor(container) {
        this.container = container;
        this.gridElement = null;
        this.cellElements = [];
    }

    // 创建8x8游戏网格的DOM结构
    createGrid() {
        // 获取游戏网格容器
        this.gridElement = this.container.querySelector('#game-grid');
        
        if (!this.gridElement) {
            console.error('找不到游戏网格容器');
            return;
        }

        // 清空现有内容
        this.gridElement.innerHTML = '';
        
        // 初始化单元格元素数组
        this.cellElements = [];
        for (let x = 0; x < 8; x++) {
            this.cellElements[x] = [];
        }

        // 创建64个单元格元素
        for (let y = 0; y < 8; y++) {
            for (let x = 0; x < 8; x++) {
                const cellElement = this.createCellElement(x, y);
                this.gridElement.appendChild(cellElement);
                this.cellElements[x][y] = cellElement;
            }
        }

        console.log('游戏网格DOM创建完成');
    }

    // 创建单个单元格元素
    createCellElement(x, y) {
        const cellDiv = document.createElement('div');
        cellDiv.className = 'ghost-cell';
        cellDiv.dataset.x = x;
        cellDiv.dataset.y = y;
        cellDiv.id = `cell-${x}-${y}`;

        // 创建小鬼图标容器
        const ghostIcon = document.createElement('div');
        ghostIcon.className = 'ghost-icon';
        cellDiv.appendChild(ghostIcon);

        return cellDiv;
    }

    // 渲染单个单元格
    renderCell(cell, x, y) {
        const cellElement = this.getCellElement(x, y);
        if (!cellElement) {
            console.error(`找不到单元格元素 (${x}, ${y})`);
            return;
        }

        const ghostIcon = cellElement.querySelector('.ghost-icon');
        if (!ghostIcon) {
            console.error(`找不到小鬼图标元素 (${x}, ${y})`);
            return;
        }

        // 移除所有类型样式
        for (let i = 0; i < 5; i++) {
            ghostIcon.classList.remove(`ghost-type-${i}`);
        }

        // 根据单元格类型设置样式
        if (cell.type >= 0 && cell.type <= 4) {
            ghostIcon.classList.add(`ghost-type-${cell.type}`);
            ghostIcon.textContent = this.getGhostEmoji(cell.type);
            cellElement.style.opacity = '1';
        } else {
            // 空单元格
            ghostIcon.textContent = '';
            cellElement.style.opacity = '0.3';
        }

        // 更新单元格的DOM元素引用
        cell.element = cellElement;
    }

    // 获取小鬼表情符号
    getGhostEmoji(type) {
        const emojis = ['👻', '🎃', '💀', '🦇', '🕷️'];
        return emojis[type] || '👻';
    }

    // 获取指定位置的单元格元素
    getCellElement(x, y) {
        if (x >= 0 && x < 8 && y >= 0 && y < 8 && this.cellElements[x]) {
            return this.cellElements[x][y];
        }
        return null;
    }

    // 渲染整个网格
    renderGrid(gameBoard) {
        for (let x = 0; x < 8; x++) {
            for (let y = 0; y < 8; y++) {
                const cell = gameBoard.getCell(x, y);
                if (cell) {
                    this.renderCell(cell, x, y);
                }
            }
        }
    }

    // 高亮显示单元格
    highlightCell(x, y) {
        const cellElement = this.getCellElement(x, y);
        if (cellElement) {
            cellElement.classList.add('selected');
        }
    }

    // 移除所有高亮
    removeHighlight() {
        const selectedCells = this.gridElement.querySelectorAll('.ghost-cell.selected');
        selectedCells.forEach(cell => {
            cell.classList.remove('selected');
        });
    }

    // 移除指定单元格的高亮
    removeHighlightFromCell(x, y) {
        const cellElement = this.getCellElement(x, y);
        if (cellElement) {
            cellElement.classList.remove('selected');
        }
    }

    // 显示匹配效果
    showMatchEffect(matches) {
        return new Promise((resolve) => {
            matches.forEach(match => {
                match.cells.forEach(cell => {
                    const cellElement = this.getCellElement(cell.x, cell.y);
                    if (cellElement) {
                        cellElement.classList.add('matching');
                    }
                });
            });

            // 匹配动画完成后移除效果
            setTimeout(() => {
                const matchingCells = this.gridElement.querySelectorAll('.ghost-cell.matching');
                matchingCells.forEach(cell => {
                    cell.classList.remove('matching');
                });
                resolve();
            }, 800);
        });
    }

    // 显示新小鬼生成动画
    showNewGhostAnimation(cells) {
        return new Promise((resolve) => {
            cells.forEach(cell => {
                const cellElement = this.getCellElement(cell.x, cell.y);
                if (cellElement) {
                    cellElement.classList.add('new-ghost');
                }
            });

            // 动画完成后移除类
            setTimeout(() => {
                const newGhostCells = this.gridElement.querySelectorAll('.ghost-cell.new-ghost');
                newGhostCells.forEach(cell => {
                    cell.classList.remove('new-ghost');
                });
                resolve();
            }, 1000);
        });
    }

    // 显示下落动画
    showFallAnimation(moves) {
        return new Promise((resolve) => {
            moves.forEach(move => {
                const cellElement = this.getCellElement(move.to.x, move.to.y);
                if (cellElement) {
                    cellElement.classList.add('falling');
                }
            });

            // 动画完成后移除类
            setTimeout(() => {
                const fallingCells = this.gridElement.querySelectorAll('.ghost-cell.falling');
                fallingCells.forEach(cell => {
                    cell.classList.remove('falling');
                });
                resolve();
            }, 400);
        });
    }

    // 更新单元格内容
    updateCell(x, y, newType) {
        const cellElement = this.getCellElement(x, y);
        if (!cellElement) return;

        const ghostIcon = cellElement.querySelector('.ghost-icon');
        if (!ghostIcon) return;

        // 移除旧的类型样式
        for (let i = 0; i < 5; i++) {
            ghostIcon.classList.remove(`ghost-type-${i}`);
        }

        // 设置新的类型样式
        if (newType >= 0 && newType <= 4) {
            ghostIcon.classList.add(`ghost-type-${newType}`);
            ghostIcon.textContent = this.getGhostEmoji(newType);
            cellElement.style.opacity = '1';
        } else {
            ghostIcon.textContent = '';
            cellElement.style.opacity = '0.3';
        }
    }

    // 获取单元格位置（从DOM元素）
    getCellPosition(element) {
        const x = parseInt(element.dataset.x);
        const y = parseInt(element.dataset.y);
        
        if (isNaN(x) || isNaN(y)) {
            return null;
        }
        
        return { x, y };
    }

    // 添加单元格点击事件监听器
    addCellClickListener(callback) {
        if (!this.gridElement) return;

        this.gridElement.addEventListener('click', (event) => {
            const cellElement = event.target.closest('.ghost-cell');
            if (cellElement) {
                const position = this.getCellPosition(cellElement);
                if (position) {
                    callback(position, cellElement);
                }
            }
        });
    }

    // 添加触摸事件监听器
    addTouchListener(callback) {
        if (!this.gridElement) return;

        let touchStartPos = null;
        let touchStartTime = 0;

        // 触摸开始
        this.gridElement.addEventListener('touchstart', (event) => {
            event.preventDefault();
            const touch = event.touches[0];
            touchStartPos = { x: touch.clientX, y: touch.clientY };
            touchStartTime = Date.now();
            
            const element = document.elementFromPoint(touch.clientX, touch.clientY);
            const cellElement = element?.closest('.ghost-cell');
            
            if (cellElement) {
                const position = this.getCellPosition(cellElement);
                if (position) {
                    callback(position, cellElement);
                }
            }
        }, { passive: false });

        // 触摸移动（用于滑动交换）
        this.gridElement.addEventListener('touchmove', (event) => {
            event.preventDefault();
        }, { passive: false });

        // 触摸结束（处理滑动手势）
        this.gridElement.addEventListener('touchend', (event) => {
            event.preventDefault();
            
            if (!touchStartPos || event.changedTouches.length === 0) return;
            
            const touch = event.changedTouches[0];
            const touchEndPos = { x: touch.clientX, y: touch.clientY };
            const touchDuration = Date.now() - touchStartTime;
            
            // 计算滑动距离和方向
            const deltaX = touchEndPos.x - touchStartPos.x;
            const deltaY = touchEndPos.y - touchStartPos.y;
            const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
            
            // 如果是快速滑动且距离足够，处理为滑动交换
            if (touchDuration < 300 && distance > 30) {
                const startElement = document.elementFromPoint(touchStartPos.x, touchStartPos.y);
                const startCellElement = startElement?.closest('.ghost-cell');
                
                if (startCellElement) {
                    const startPos = this.getCellPosition(startCellElement);
                    if (startPos) {
                        // 确定滑动方向
                        let targetPos = null;
                        if (Math.abs(deltaX) > Math.abs(deltaY)) {
                            // 水平滑动
                            targetPos = {
                                x: startPos.x + (deltaX > 0 ? 1 : -1),
                                y: startPos.y
                            };
                        } else {
                            // 垂直滑动
                            targetPos = {
                                x: startPos.x,
                                y: startPos.y + (deltaY > 0 ? 1 : -1)
                            };
                        }
                        
                        // 检查目标位置是否有效
                        if (targetPos.x >= 0 && targetPos.x < 8 && targetPos.y >= 0 && targetPos.y < 8) {
                            const targetElement = this.getCellElement(targetPos.x, targetPos.y);
                            if (targetElement) {
                                callback(targetPos, targetElement);
                            }
                        }
                    }
                }
            }
            
            touchStartPos = null;
        }, { passive: false });
    }

    // 设置网格可见性
    setGridVisibility(visible) {
        if (this.gridElement) {
            this.gridElement.style.display = visible ? 'grid' : 'none';
        }
    }

    // 更新分数显示
    updateScore(score) {
        const scoreElement = this.container.querySelector('#score');
        if (scoreElement) {
            scoreElement.textContent = score.toLocaleString();
            
            // 添加分数更新动画
            scoreElement.classList.add('score-update');
            setTimeout(() => {
                scoreElement.classList.remove('score-update');
            }, 300);
        }
    }

    // 更新时间显示
    updateTimer(timeInSeconds) {
        const timeElement = this.container.querySelector('#time');
        if (timeElement) {
            const minutes = Math.floor(timeInSeconds / 60);
            const seconds = timeInSeconds % 60;
            const formattedTime = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            timeElement.textContent = formattedTime;
        }
    }

    // 绑定重新开始按钮事件
    bindRestartButton(callback) {
        const restartBtn = this.container.querySelector('#restart-btn');
        if (restartBtn) {
            restartBtn.addEventListener('click', callback);
        }
    }

    // 显示游戏覆盖层
    showOverlay(title, message, showContinueButton = true) {
        const overlay = this.container.querySelector('#game-overlay');
        const overlayTitle = this.container.querySelector('#overlay-title');
        const overlayMessage = this.container.querySelector('#overlay-message');
        const continueBtn = this.container.querySelector('#continue-btn');

        if (overlay && overlayTitle && overlayMessage) {
            overlayTitle.textContent = title;
            overlayMessage.textContent = message;
            
            if (continueBtn) {
                continueBtn.style.display = showContinueButton ? 'block' : 'none';
            }
            
            overlay.style.display = 'flex';
        }
    }

    // 隐藏游戏覆盖层
    hideOverlay() {
        const overlay = this.container.querySelector('#game-overlay');
        if (overlay) {
            overlay.style.display = 'none';
        }
    }

    // 绑定继续按钮事件
    bindContinueButton(callback) {
        const continueBtn = this.container.querySelector('#continue-btn');
        if (continueBtn) {
            continueBtn.addEventListener('click', callback);
        }
    }

    // 显示游戏状态消息
    showStatusMessage(message, duration = 2000) {
        // 创建状态消息元素
        let statusElement = this.container.querySelector('.status-message');
        
        if (!statusElement) {
            statusElement = document.createElement('div');
            statusElement.className = 'status-message';
            this.container.appendChild(statusElement);
        }

        statusElement.textContent = message;
        statusElement.style.display = 'block';
        statusElement.classList.add('show');

        // 自动隐藏消息
        setTimeout(() => {
            statusElement.classList.remove('show');
            setTimeout(() => {
                statusElement.style.display = 'none';
            }, 300);
        }, duration);
    }

    // 更新连击显示
    updateCombo(combo) {
        if (combo > 1) {
            this.showStatusMessage(`连击 x${combo}!`, 1500);
        }
    }

    // 显示加载状态
    showLoading(message = '游戏加载中...') {
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'game-loading';
        loadingDiv.innerHTML = `
            <div class="loading-spinner"></div>
            <span>${message}</span>
        `;
        
        if (this.gridElement) {
            this.gridElement.appendChild(loadingDiv);
        }
    }

    // 隐藏加载状态
    hideLoading() {
        const loadingElement = this.container.querySelector('.game-loading');
        if (loadingElement) {
            loadingElement.remove();
        }
    }

    // 显示错误信息
    showError(message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'game-error';
        errorDiv.innerHTML = `
            <h3>游戏错误</h3>
            <p>${message}</p>
            <button onclick="location.reload()" class="restart-btn">重新加载</button>
        `;
        
        if (this.gridElement) {
            this.gridElement.appendChild(errorDiv);
        }
    }

    // 防抖函数
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 节流函数
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }

    // 优化的渲染方法（批量更新）
    batchRenderCells(updates) {
        // 使用 requestAnimationFrame 进行批量更新
        requestAnimationFrame(() => {
            updates.forEach(({ x, y, cell }) => {
                this.renderCell(cell, x, y);
            });
        });
    }

    // 检查设备性能
    checkPerformance() {
        const isLowEnd = navigator.hardwareConcurrency <= 2 || 
                        navigator.deviceMemory <= 2 ||
                        /Android.*Chrome\/[0-5]/.test(navigator.userAgent);
        
        if (isLowEnd) {
            // 为低端设备禁用一些动画
            document.body.classList.add('low-performance');
            console.log('检测到低端设备，已启用性能优化模式');
        }
        
        return !isLowEnd;
    }

    // 预加载资源
    preloadResources() {
        // 预创建一些DOM元素以提高性能
        const fragment = document.createDocumentFragment();
        for (let i = 0; i < 10; i++) {
            const cell = this.createCellElement(0, 0);
            fragment.appendChild(cell);
        }
        // 不添加到DOM，只是预创建
    }

    // 清空网格
    clearGrid() {
        if (this.gridElement) {
            this.gridElement.innerHTML = '';
            this.cellElements = [];
        }
    }
}